﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DAL;
using BOL;
using System.Data.Linq;
using System.Data.SqlClient;
using Website.Logger;
using UtilityExtensions;

namespace UILGestion.ObraAdmin.RendicionCaja
{
    public partial class RendicionListForm : System.Web.UI.Page
    {

        public RendicionListForm()
        {
            bol = new RendicionBL();
        }

        private RendicionBL bol;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                try
                {
                    
                    int idEmpleado = (int)Session["idEmpleado"];
                    //if (idEmpleado == 1 | idEmpleado == 32 | idEmpleado == 50)
                    //{
                        idObra.Value = (string)Request.QueryString["idObra"];
                        menuObraCtrl1.loadMenu(int.Parse(idObra.Value), Request.AppRelativeCurrentExecutionFilePath);
                        FormatForm();
                    //}
                    


                }
                catch (SqlException sqlex)
                {
                    WebServerSideSqlError.Log(sqlex);

                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


                }
                catch (Exception ex)
                {
                    WebServerSideError.Log(ex);
                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                         "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

                }


            }
        }
        private void DataBindItem()
        {
            nuevoRendicionBtn.Enabled=false;
            //si la ultima rendicion esta cerrado
                
            
            var rendicion = new Rendicion();
            short itemRendicionUlt = rendicion.GetUltimoItemRendicion(DbUtil.Db, cajaDDL.SelectedValue.ToInt());

            if (itemRendicionUlt == 0)
            {
                nuevoRendicionBtn.Enabled = true;
            }
            else
            {

                rendicion = DbUtil.Db.Rendicions.Single(p => p.idCaja == cajaDDL.SelectedValue.ToInt() & p.itemRendicion == itemRendicionUlt);
                if (rendicion.idEstado == 41 | rendicion.idEstado == 42)  //aprobado  o facturado
                {
                    nuevoRendicionBtn.Enabled = true;
                }

            }
                
            estructuraGridView.DataSource = bol.getRecepcionList(cajaDDL.SelectedValue.ToInt());
            estructuraGridView.DataBind();
            
            resetEmpty();
            setEstadistica();
            

        }

        private void FormatForm()
        {
            ShowAllComboBox();
            //restricionesForm();

            DataBindItem();
            setEstadistica();

         
   //       
        }
        protected void ShowAllComboBox()
        {
            
            cajaDDL.DataValueField = "idInternal";
            cajaDDL.DataTextField = "descripcion";
            cajaDDL.DataSource = new ListValueBL().GetCajaChica(idObra.Value.ToInt());
            cajaDDL.DataBind();

        }
        private void setFooterRow()
        {
            
            //DropDownList monedaDropDownList = ((DropDownList)proveedorGridView.FooterRow.FindControl("monedaInsertDropDownList"));
            
            //DropDownList obraInsertDropDownList =
            //    ((DropDownList)estructuraGridView.FooterRow.FindControl("Estructura2DropDownList"));


            //obraInsertDropDownList.DataValueField = "idInternal";
            //obraInsertDropDownList.DataTextField = "descripcion";
            //obraInsertDropDownList.DataSource = DbUtil.Db.Estructuras;
            //obraInsertDropDownList.DataBind();




        }

        private void resetEmpty()
        {
            if (estructuraGridView.Rows.Count == 0)
            {
                List<RendicionInfo> itemList0 = new List<RendicionInfo>();
                RendicionInfo itemcero = new RendicionInfo();

                itemList0.Add(itemcero);
                estructuraGridView.DataSource = itemList0;
                estructuraGridView.DataBind();
                estructuraGridView.Rows[0].Visible = false;
            }

        }

        protected void gvestructura_RowDataBound(Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    GridView gv = (GridView)e.Row.FindControl("recursoEGridView");

            //    gv.DataSource = new EstructuraCostoBL().GetRecursoEstructuraCostoItem((e.Row.DataItem as EstructuraCostoListInfo).idInternal);
            //    gv.DataBind();
            //}
        }



        protected void onSelectChanged(object sender, EventArgs e)
        {
            try
            {
                this.DataBindItem();  
                
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void cargaRecursos_click(object sender, EventArgs e)
        {
            try
            {
                ImageButton lnkdivrecurso = (ImageButton)sender;
                int idEC=int.Parse(lnkdivrecurso.CommandName);
                int rowindex=int.Parse(lnkdivrecurso.CommandArgument);
                string div="div"+idEC.ToString();
                string script = String.Empty;

                Panel divcol = (Panel)estructuraGridView.Rows[rowindex].FindControl("divgrilla");

                if (lnkdivrecurso.ImageUrl == "../Images/expand_button.png")
                {
                    GridView gv = (GridView)estructuraGridView.Rows[rowindex].FindControl("recursoEGridView");
                UpdatePanel panel = (UpdatePanel)estructuraGridView.Rows[rowindex].FindControl("recursoUpdatePanel");
                   
                   
                        
                gv.DataSource = new EstructuraCostoBL().GetRecursoEstructuraCostoItem(idEC);
                gv.DataBind();

                lnkdivrecurso.ImageUrl = "../Images/expand_button_down.png";
                   divcol.Style.Add("display","inline");

              
          

                panel.Update();
                }else
                {
                   lnkdivrecurso.ImageUrl = "../Images/expand_button.png";
                  divcol.Style.Add("display", "none");
                }


               
                
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        

      

        private void setEstadistica()
        {
            //por ahora todo es en soles
            
            //SOLO LOS SOLES
            var monedaD=DbUtil.Db.Monedas.Single(p=>p.idInternal==4);
            var moneda=DbUtil.Db.Monedas.Single(p=>p.idInternal==3);
            var q= (DbUtil.Db.Rendicions.Where(a=> a.idObra==idObra.Value.ToInt() & a.Caja.idMoneda==3)) ;
            var qD= (DbUtil.Db.Rendicions.Where(a=> a.idObra==idObra.Value.ToInt() & a.Caja.idMoneda==4)) ;
                   
            decimal ingreso=(q.Count()>0?q.Sum(p=>p.toalIngreso):0);
            decimal ingresoD=(qD.Count()>0?qD.Sum(p=>p.toalIngreso):0);
            decimal deposito=(q.Count()>0?q.Sum(p=>p.totalDeposito):0);
            decimal depositoD=(qD.Count()>0?qD.Sum(p=>p.totalDeposito):0);

            totalRendicionLbl.Text = "{0} {1:N}".Fmt(moneda.simbol, ingreso);
            totalDesembolsoLbl.Text = "{0} {1:N}".Fmt(moneda.simbol, deposito);
            totalPendienteLBL.Text = "{0} {1:N}".Fmt(moneda.simbol, ingreso - deposito);

            totalRendicionDOL.Text = "{0} {1:N}".Fmt(monedaD.simbol, ingresoD);
            totalDesembolsoDOL.Text = "{0} {1:N}".Fmt(monedaD.simbol, depositoD);
            totalPendienteDOL.Text = "{0} {1:N}".Fmt(monedaD.simbol, ingresoD - depositoD);

            
            totalesUpdatePanel.Update();
            
            
        }
        protected void nuevoButton_Click(object sender, EventArgs e)
        {

            estructuraGridView.FooterRow.Visible = true;


            ///Response.Redirect("PresupuestoAdicionInsertForm.aspx?idObra=" + idObra.Value, true);
        }
        //protected void AddLinkButton_onClick(object sender, EventArgs e)
        //{


        //    if (((Button)sender).ID == "addProvAdd")
        //    {

        //        string descripcion = ((TextBox)estructuraGridView.FooterRow.FindControl("descripcionEditTextbox")).Text;
        //        int idUsuario = (int)Session["idEmpleado"];
        //        Rendicion ec = new Rendicion();

        //        bol.a(DateTime.Now,
        //            descripcion,
        //            idObra.Value.ToInt(), 
        //            1);

        //        DataBindItem();
        //        estructuraUpdate.Update();
        //    }
        //    if (((Button)sender).ID == "cancelLinkButton")
        //    {
        //        estructuraGridView.FooterRow.Visible = false;
        //        ((TextBox)estructuraGridView.
        //            FooterRow.FindControl("descripcionEditTextbox")).Text="";
        //    }

         

        //}

        //protected void Deleteitem(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        ImageButton lnkRemove = (ImageButton)sender;

        //        Rendicion ren = DbUtil.Db.Rendicions.SingleOrDefault(p => p.idInternal == lnkRemove.CommandArgument.ToInt());
        //        DbUtil.Db.Rendicions.DeleteOnSubmit(ren);
        //        DbUtil.Db.SubmitChanges();
        //        DataBindItem();
        //        setEstadistica();
        //        estructuraUpdate.Update();
        //    }
        //    catch (SqlException sqlex)
        //    {
        //        WebServerSideSqlError.Log(sqlex);

        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //         "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


        //    }
        //    catch (Exception ex)
        //    {
        //        WebServerSideError.Log(ex);
        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //             "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

        //    }

        //}

        //protected void EditItem(object sender, GridViewEditEventArgs e)
        //{
        //    try
        //    {
        //        estructuraGridView.EditIndex = e.NewEditIndex;


        //        int parent_index = e.NewEditIndex;
        //        DataBindItem();
        //        estructuraGridView.FooterRow.Visible = false;

        //    }
        //    catch (SqlException sqlex)
        //    {
        //        WebServerSideSqlError.Log(sqlex);
        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //         "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


        //    }
        //    catch (Exception ex)
        //    {
        //        WebServerSideError.Log(ex);
        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //         "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

        //    }
        //}

        //protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        //{
        //    try
        //    {
        //        string idInternal = ((GridView)sender).DataKeys[e.RowIndex].Values[0].ToString();

        //       string descripcion = ((TextBox)estructuraGridView.Rows[e.RowIndex].FindControl("descripcionEditTextBox")).Text;
              

        //        Rendicion EC = DbUtil.Db.Rendicions.Single(p => p.idInternal == int.Parse(idInternal));

        //        EC.descripcion = descripcion;
                
        //        DbUtil.Db.SubmitChanges();
        //        estructuraGridView.EditIndex = -1;
        //        DataBindItem();
        //        estructuraUpdate.Update();
        //    }
        //    catch (SqlException sqlex)
        //    {
        //        WebServerSideSqlError.Log(sqlex);
        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //         "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


        //    }
        //    catch (Exception ex)
        //    {
        //        WebServerSideError.Log(ex);
        //        ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
        //         "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

        //    }

        //}


        protected void editEcostoButton_click(object sender, EventArgs e)
        {
            int idInternal = int.Parse(((LinkButton)sender).CommandArgument.ToString());
            Response.Redirect("RendicionEditForm.aspx?idObra=" + idObra.Value + "&id=" + idInternal.ToString());
            


        }


        protected void CancelEditItem(object sender, GridViewCancelEditEventArgs e)
        {
            estructuraGridView.EditIndex = -1;
            DataBindItem();
            estructuraUpdate.Update();
            
        }

        protected void actualizarbtn_Click(object sender, EventArgs e)
        {
            DataBindItem();
            setEstadistica();
        }

        protected void estructuraGridView_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        protected void Deleteitem(object sender, EventArgs e)
        {
            try
            {
                ImageButton lnkRemove = (ImageButton)sender;

                
                bol.Delete(int.Parse(lnkRemove.CommandArgument.ToString()));
                DataBindItem();
                setEstadistica();
                estructuraUpdate.Update();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void loadRendicion(object sender, EventArgs e)
        {
            try
            {
                if (cajaDDL.SelectedValue.ToInt() != 0)
                {
                    RendicionAddPanel1.Load(DbUtil.Db.Cajas.Single(p => p.idInternal == cajaDDL.SelectedValue.ToInt()));
                    SeleccionUpdatePanel.Update();
                    depositoModalpopupextender.Show();
                }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        protected void nuevoRendicionBtn_Click(object sender, EventArgs e)
        {
            try
            {


                var deposito = RendicionAddPanel1.depositoInfo;
                var rendicion = RendicionAddPanel1.rendicionInfo;

                RendicionBL bol = new RendicionBL();
                bol.Add(rendicion.descripcion,
                         rendicion.idObra,
                         rendicion.idCaja,
                         deposito.fecha,
                         deposito.idTipoEntrega,
                         deposito.numDocumento,
                         deposito.total);

                DataBindItem();
                depositoModalpopupextender.Hide();
            }

            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page),
                     "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }
        }

        protected void cajaDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            if (cajaDDL.SelectedValue.ToInt() != null)
            {
                DataBindItem();
                
            }
        }
    }
}